/***
This do-file combines all ACS County-level variables into a single cleaned dataset.
***/

*-------------------------------------------------------------------------------
* Set up
*-------------------------------------------------------------------------------

* Set $root
project figstabs, root
if (r(buildrunning)==0) include "${root}/code/config_interactive.do"

*-------------------------------------------------------------------------------
* Run cleaning code for each ACS variable
*-------------------------------------------------------------------------------

project, do("${root}/code/ACS 2014-2018 5-Year County/ACS 2014-2018 Gini - Cleaning.do")
project, do("${root}/code/ACS 2014-2018 5-Year County/ACS 2014-2018 Median 2BR Rent - Cleaning.do")
project, do("${root}/code/ACS 2014-2018 5-Year County/ACS 2014-2018 Median Household Income - Cleaning.do")
project, do("${root}/code/ACS 2014-2018 5-Year County/ACS 2014-2018 Population - Cleaning.do")
project, do("${root}/code/ACS 2014-2018 5-Year County/ACS 2014-2018 Share Below Poverty Line - Cleaning.do")

*-------------------------------------------------------------------------------
* Combine ACS variables
*-------------------------------------------------------------------------------

project, uses("${root}/data/derived/ACS 2014-2018 5-Year County/Individual Variables/ACS 2014-2018 Population.dta")
use "${root}/data/derived/ACS 2014-2018 5-Year County/Individual Variables/ACS 2014-2018 Population.dta", clear

foreach file in "Median Household Income" "Median 2BR Rent" "Gini Index" "Share Below Poverty Line" {
	project, uses("${root}/data/derived/ACS 2014-2018 5-Year County/Individual Variables/ACS 2014-2018 `file'.dta")
	merge 1:1 county_fips using "${root}/data/derived/ACS 2014-2018 5-Year County/Individual Variables/ACS 2014-2018 `file'.dta", assert(3) nogen
}

* Split county_name variable
split county_name, p(", ")
drop county_name county_name2
rename county_name1 county_name

replace county_name = "Dona Ana County" if county_name == "Doï¿½a Ana County"

* Create state variables
gen state_fips = int(county_fips / 1000)
statastates, fips(state_fips)

* Assert not matched iff Puerto Rico, and drop Puerto Rico
assert (state_fips == 72) == (_merge != 3)
drop if _merge != 3
drop _merge

*-------------------------------------------------------------------------------
* Save final file
*-------------------------------------------------------------------------------

save "${root}/data/derived/ACS 2014-2018 5-Year County/ACS 2014-2018 County.dta", replace
project, creates("${root}/data/derived/ACS 2014-2018 5-Year County/ACS 2014-2018 County.dta")
